import React, { useEffect, useState } from "react";
import {
  Form,
  Input,
  Upload,
  Button,
  Row,
  Col,
  TreeSelect,
  Skeleton,
  InputNumber,
  DatePicker,
  Switch,
} from "antd";
import { UploadOutlined } from "@ant-design/icons";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import dictionarysApi from "../../../apis/dictionarysApi";
import recursion from "../../../utils/recursion";
import goodsApi from "../../../apis/goodsApi"; // 假设这里使用商品API
import { getImagePath2, promptResult2 } from "../../../utils/common";
import ComponentHeader from "../../../components/Page/ComponentHeader";
import { useParams } from "react-router-dom";
import dayjs from "dayjs";

const GoodEdit = () => {
  useCloseLoadingOnMount();
  const [form] = Form.useForm();
  const [goods, setGoods] = useState({});
  const [loading, setLoading] = useState(true);
  const [loadingBtn, setLoadingBtn] = useState(false);
  const params = useParams();
  const [goodTypes, setGoodTypes] = useState([]);
  const [supplierShopNameOptions, setSupplierShopNameOptions] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await dictionarysApi.getDictionaryBySearchKey(
        "good_category"
      );
      recursion(res.data, "children", (tree) => {
        if (tree.children.length > 0) tree.selectable = false;
      });
      if (res.status >= 0) {
        setGoodTypes(res.data);
      }
      const res2 = await goodsApi.getGoodsDetail(params.id); // 使用商品API获取详情
      if (res2.status >= 0) {
        setGoods(res2.data);
      }
      setLoading(false);
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (!loading) {
      form.setFieldsValue({
        ...goods,
        shopName: goods.supplierShopName,
        isDirectly: goods.isDirectly === 0 ? false : true,
        isShelve: goods.isShelve === 0 ? false : true,
        birthday: dayjs(goods.birthdayStr),
        photo: goods.photo.split(",").map((d) => {
          return {
            name: d,
            url: getImagePath2(goods.id, d),
            thumbUrl: getImagePath2(goods.id, d),
            status: "done",
          };
        }),
        detailImages: goods.detailImages.split(",").map((d) => {
          return {
            name: d,
            url: getImagePath2(goods.id, d),
            thumbUrl: getImagePath2(goods.id, d),
            status: "done",
          };
        }),
      });
    }
  }, [goods]);

  const onFinish = async (values) => {
    const formData = new FormData();
    for (var key in values) {
      if (
        ![
          "photo",
          "detailImages",
          "birthday",
          "isDirectly",
          "isShelve",
          "isPromote",
        ].includes(key)
      )
        formData.append(key, values[key]);
    }
    for (var key in values.photo) {
      var photo = values.photo[key];
      if (photo.status !== "done") {
        formData.append("photo", photo.originFileObj);
      }
    }
    for (var key in values.detailImages) {
      var detailImage = values.detailImages[key];
      if (detailImage.status !== "done") {
        formData.append("detailImages", detailImage.originFileObj);
      } else {
        formData.append("retainDetailImages", detailImage.name);
      }
    }
    formData.append("id", params.id);
    formData.append("birthday", values.birthday.format("YYYY-MM-DD HH:mm:ss"));
    formData.append("isDirectly", values.isDirectly ? 1 : 0);
    formData.append("isShelve", values.isShelve ? 1 : 0);
    formData.append("isPromote", values.isPromote ? 1 : 0);
    await promptResult2(goodsApi.updateGoods(formData), setLoadingBtn);
  };

  return (
    <>
      {loading ? (
        <Skeleton active paragraph={{ rows: 10 }} />
      ) : (
        <div className="body-container1">
          <ComponentHeader title="商品编辑" marginBottom />
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
            initialValues={{
              isDirectly: false,
              isShelve: false,
              isPromote: false,
              topLevel: 0,
              inventory: 0,
            }}
          >
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="商品名称"
                  name="name"
                  rules={[{ required: true, message: "请输入商品名称" }]}
                >
                  <Input placeholder="请输入商品名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="商品价格"
                  name="price"
                  rules={[{ required: true, message: "请输入商品价格" }]}
                >
                  <InputNumber
                    style={{ width: "100%" }}
                    min={0.01}
                    step={1}
                    precision={2}
                    formatter={(value) => `¥ ${value}`}
                    placeholder="请输入商品价格"
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="商品类别"
                  name="goodTypeId"
                  rules={[{ required: true, message: "请选择商品类别" }]}
                >
                  <TreeSelect
                    treeData={goodTypes}
                    fieldNames={{ label: "value", value: "id" }}
                    placeholder="请选择商品类别"
                  ></TreeSelect>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="库存"
                  name="inventory"
                  rules={[{ required: true, message: "请输入库存" }]}
                >
                  <InputNumber
                    min={0}
                    style={{ width: "100%" }}
                    placeholder="请输入库存"
                  />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              label="商品描述"
              name="description"
              rules={[{ required: true, message: "请输入商品描述" }]}
            >
              <Input.TextArea rows={4} placeholder="请输入商品描述" />
            </Form.Item>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="生产日期"
                  name="birthday"
                  rules={[{ required: true, message: "请选择生产日期" }]}
                >
                  <DatePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    style={{ width: "100%" }}
                    placeholder="请选择生产日期"
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="保质期（天）"
                  name="expiryday"
                  rules={[{ required: true, message: "请输入保质期" }]}
                >
                  <InputNumber
                    min={1}
                    style={{ width: "100%" }}
                    placeholder="请输入保质期"
                  />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              label="商品规格"
              name="specs"
              rules={[{ required: true, message: "请输入商品规格" }]}
            >
              <Input.TextArea
                rows={2}
                onBlur={(e) =>
                  form.setFieldValue(
                    "specs",
                    e.target.value.replaceAll("：", ":").replaceAll("；", ";")
                  )
                }
                placeholder="示例：颜色:红色;尺寸:XL"
              />
            </Form.Item>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="是否直营"
                  name="isDirectly"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="是否上架" name="isShelve">
                  <Switch />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              label="封面图片"
              name="photo"
              rules={[{ required: true, message: "请上传封面图片" }]}
              valuePropName="fileList" // 指定值来源为组件的 fileList 属性
              getValueFromEvent={(e) => e.fileList} // 将 onChange 的返回值转为表单字段值
            >
              <Upload
                listType="picture"
                maxCount={1}
                beforeUpload={() => false} // 阻止自动上传
              >
                <Button icon={<UploadOutlined />}>选择文件</Button>
              </Upload>
            </Form.Item>

            <Form.Item
              label="详情图片"
              name="detailImages"
              rules={[{ required: true, message: "请上传详情图片" }]}
              valuePropName="fileList" // 指定值来源为组件的 fileList 属性
              getValueFromEvent={(e) => e.fileList} // 将 onChange 的返回值转为表单字段值
            >
              <Upload listType="picture" multiple beforeUpload={() => false}>
                <Button icon={<UploadOutlined />}>选择文件</Button>
              </Upload>
            </Form.Item>

            <Form.Item
              label="置顶级别"
              name="topLevel"
              rules={[{ required: true, message: "请输入置顶级别" }]}
            >
              <InputNumber
                min={0}
                style={{ width: "100%" }}
                placeholder="请输入置顶级别"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                loading={loadingBtn}
                htmlType="submit"
                style={{ width: 120 }}
              >
                提交
              </Button>
            </Form.Item>
          </Form>
        </div>
      )}
    </>
  );
};

export default GoodEdit;
